package com.peanut.baby.mvp.mydata.daily;

import android.app.Activity;

import com.peanut.baby.InitManager;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.CalendarRecord;

import java.util.List;

import cn.nekocode.rxlifecycle.RxLifecycle;
import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/8/28.
 */

public class DailyDataPresenter implements DailyDataFragmentContract.Presenter{
    DailyDataFragmentContract.View view;
    Activity activity;
    public DailyDataPresenter(DailyDataFragmentContract.View view,Activity activity) {
        this.view = view;
        this.activity = activity;
    }

    @Override
    public void getRecordList(int pageNo, int pageSize) {
        Observable obs = RetrofitClient.getInstance().getMyData(InitManager.getInstance().getUserId(),
                pageNo,
                pageSize,
                InitManager.getInstance().getUser().userToken);
        obs.compose(BaseScheduler.<List<CalendarRecord>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<List<CalendarRecord>>() {
            @Override
            protected void onHandleSuccess(List<CalendarRecord> o) {
                updateDatabaseInSubThread(o);
            }

            @Override
            protected void onHandleError(String code, String msg) {
                view.onGetListFailed(msg);
            }
        });
    }

    private void updateDatabaseInSubThread(final List<CalendarRecord> o){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(o != null && !o.isEmpty()){
                    for(int i=0;i<o.size();i++){
                        DBManager.getInstance().updateCalendarRecord(o.get(i));
                    }
                }
                view.onListGet(o);

            }
        }).start();
    }
}
